package edu.gduf.service.impl;

import edu.gduf.dao.StudentDao;
import edu.gduf.domain.ResultInfo;
import edu.gduf.service.PictureService;
import edu.gduf.utils.FileUtil;
import org.apache.ibatis.io.Resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Demo Class
 *
 * @author 古市
 * @date 2020-12-21 21:31
 **/
@Service
public class PictureServiceImpl implements PictureService {

    final String FILE_TYPE_JUDGE = ".jpg";

    private StudentDao studentDao;


    @Autowired
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    @Override
    public ResultInfo savePicture(MultipartFile[] files) {
        List<String> warningPicture = new ArrayList<>();
        for (MultipartFile file : files) {
            //获取上传文件的初始名称
            String originalFilename = file.getOriginalFilename();
            //获取最后一个.的位置
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件的后缀
            String suffix = originalFilename.substring(lastIndexOf);
            if (!FILE_TYPE_JUDGE.equalsIgnoreCase(suffix)){
                warningPicture.add(originalFilename+": 文件格式不正确");
                continue;
            }
            //获取文件的前缀
            String prefix = originalFilename.substring(0,lastIndexOf);
            if (studentDao.findStudentByNum(prefix) == null){
                warningPicture.add(originalFilename+": 该学生不存在，请重新检查学号");
                continue;
            }

            //设置上传文件的保存地址目录
            File path = null;
            path = new File(FileUtil.class.getResource("/").getPath());
            String dirPath = path + "/picture/";
            File filePath = new File(dirPath);
            //如果保存地址目录不存在，则创建此目录
            if (!filePath.exists()){
                filePath.mkdirs();
            }
            String realPath = dirPath + originalFilename;
            try {
                file.transferTo(new File(realPath));
            } catch (IOException e) {
                e.printStackTrace();
                warningPicture.add(originalFilename+"写入文件出现异常");
            }
        }
        if (warningPicture.size() == 0){
            return ResultInfo.successInfo("成功录入"+files.length+"张照片");
        }else if (warningPicture.size() < files.length){
            return ResultInfo.warnInfo("成功录入"+(files.length - warningPicture.size())+"张照片,"+warningPicture.size()+"份录入失败", warningPicture);
        }
        return ResultInfo.failInfo("录入失败", warningPicture);
    }
}
